using FeedReaderApp.Common;
using GalaSoft.MvvmLight;
using FeedReaderApp.DataModel;
using FeedReaderApp.Model;

namespace FeedReaderApp.ViewModel
{
    public class DataSourceAwareViewModel : ViewModelBase
    {
        public DataSourceAwareViewModel()
        {
            _isLoading = false;
        }

        protected void InitializeDataSource()
        {
            FeedsDataSource.Instance.LoadFeedsParallel(false);
            IsLoading = FeedsDataSource.Instance.IsCurrentlyLoading;
        }

        public const string IsLoadingPropertyName = "IsLoading";
        private bool _isLoading;
        public bool IsLoading
        {
            get { return _isLoading; }
            set { Set(IsLoadingPropertyName, ref _isLoading, value); }
        }

        public void RegisterDataSourceEvents()
        {
            IsLoading = FeedsDataSource.Instance.IsCurrentlyLoading;
            FeedsDataSource.Instance.FeedItemsLoadingCompleted += OnFeedItemsLoadingCompleted;
        }

        public void DeRegisterDataSourceEvents()
        {
            FeedsDataSource.Instance.FeedItemsLoadingCompleted -= OnFeedItemsLoadingCompleted;
        }

        private void OnFeedItemsLoadingCompleted(object sender, FeedItemsLoadingCompletedEventArgs feedItemsLoadingCompletedEventArgs)
        {
            UIDispatcher.Execute(() =>
            {
                IsLoading = false;
                OnLoadingCompleted();
            });
        }

        protected virtual void OnLoadingCompleted()
        {
        }
    }
}
